/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
var form = null;

layui.define(['form', 'layedit', 'laydate', 'zmnBind', 'xmSelect', 'upload'], function (exports) {
    let $ = layui.$;
    form = layui.form;
    let layer = layui.layer;
    let laydate = layui.laydate;
    let upload = layui.upload;
    let zmnBind = layui.zmnBind;
    let index;

    let obj = json.obj;

    let contractBeginDayObj = {
        elem: '#contractBeginDay',
        type: 'date',
    };
    if (obj.contractBeginDay != null) {
        contractBeginDayObj.value = new Date(obj.contractBeginDay);
    }
    laydate.render(contractBeginDayObj);

    let contractEndDayObj = {
        elem: '#contractEndDay',
        type: 'date',
    };
    if (obj.contractEndDay != null) {
        contractEndDayObj.value = new Date(obj.contractEndDay);
    }
    laydate.render(contractEndDayObj);

    let signDayObj = {
        elem: '#signDay',
        type: 'date',
    };
    if (obj.signDay != null) {
        signDayObj.value = new Date(obj.signDay);
    }
    laydate.render(signDayObj);

    let agentSearch = {
        init: function () {
            let searchObj = obj.staffMap[obj.agent];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }

            zmnBind.searchOperator("agent", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.agent], function(values){
                let url = "/contract/record/getStaff";
                $.ajax({
                    type: "POST", url: url,
                    dataType: "json", data: {staffId: values[0]},
                    success: function (items) {
                        console.log(items);
                        let staff = items.data;
                        if (staff.companyId != null) {
                            $('#agentCompanyId option:selected').removeAttr('selected');
                            $('#agentCompanyId option:selected').prop('selected', false);
                            $("#agentCompanyId option[value='" + staff.companyId + "']").prop("selected", true);
                            form.render();
                        } else {
                            $("#agentCompanyId").each(function(){
                                $(this).find("option").eq(0).prop("selected",true)
                            });
                        }

                        if (staff.deptOneId != null || staff.deptTwoId != null || staff.deptThrId != null) {
                            if ((staff.deptTwoId != null && staff.deptTwoId > 1) || (staff.deptThrId != null && staff.deptThrId > 1)) {
                                $("#oneDeptId option[value='" + staff.deptOneId + "']").attr("selected", "selected");
                                $("#deptId option[value='" + staff.deptTwoId + "']").attr("selected", "selected");
                            } else if ((staff.deptOneId != null && staff.deptOneId > 1)) {
                                $("#oneDeptId option[value='" + staff.deptOneId + "']").attr("selected", "selected");
                            } else {
                                $("#oneDeptId").each(function(){
                                    $(this).find("option").eq(0).prop("selected",true);
                                });
                                $("#deptId").each(function(){
                                    $(this).find("option").eq(0).prop("selected",true);
                                });
                            }
                        } else {
                            $("#oneDeptId").each(function(){
                                $(this).find("option").eq(0).prop("selected",true);
                            });
                            $("#deptId").each(function(){
                                $(this).find("option").eq(0).prop("selected",true);
                            });
                        }

                        form.render();
                    }
                });
            });
            $('#agent .xm-search-input').on('input propertychange', function () {
                searchValue = $('#agent .xm-search-input').val();
            });
        }
    };

    agentSearch.init();

    let firstAlertReceiver1Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.firstAlertReceiver1];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("firstAlertReceiver1", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.firstAlertReceiver1]);
        }
    };
    firstAlertReceiver1Search.init();

    let firstAlertReceiver2Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.firstAlertReceiver2];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("firstAlertReceiver2", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.firstAlertReceiver2]);
        }
    };
    firstAlertReceiver2Search.init();

    let firstAlertReceiver3Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.firstAlertReceiver3];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("firstAlertReceiver3", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.firstAlertReceiver3]);
        }
    };
    firstAlertReceiver3Search.init();

    // 二次预警人
    let secondAlertReceiver1Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.secondAlertReceiver1];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("secondAlertReceiver1", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.secondAlertReceiver1]);
        }
    };
    secondAlertReceiver1Search.init();

    let secondAlertReceiver2Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.secondAlertReceiver2];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("secondAlertReceiver2", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.secondAlertReceiver2]);
        }
    };
    secondAlertReceiver2Search.init();

    let secondAlertReceiver3Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.secondAlertReceiver3];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("secondAlertReceiver3", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.secondAlertReceiver3]);
        }
    };
    secondAlertReceiver3Search.init();

    // 过期预警人
    let overdueAlertReceiver1Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.overdueAlertReceiver1];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("overdueAlertReceiver1", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.overdueAlertReceiver1]);
        }
    };
    overdueAlertReceiver1Search.init();

    let overdueAlertReceiver2Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.overdueAlertReceiver2];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("overdueAlertReceiver2", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.overdueAlertReceiver2]);
        }
    };
    overdueAlertReceiver2Search.init();

    let overdueAlertReceiver3Search = {
        init: function () {
            let searchObj = obj.staffMap[obj.overdueAlertReceiver3];
            let searchValue = null;
            if (searchObj != undefined || searchObj != null) {
                searchValue = searchObj.realName;
            }
            zmnBind.searchOperator("overdueAlertReceiver3", function () {
                return {status: 2};
            }, true, false, searchValue, [obj.overdueAlertReceiver3]);
        }
    };
    overdueAlertReceiver3Search.init();

    form.render(null, "zmn-form");

    form.verify({
        isDaysNumber: function (value, item) {
            if (value !== "") {
                if (!/^[0-9]+$/.test(value)) {
                    return "预警时间设置只能是正整数";
                }
                if (value < 1) {
                    return "预警时间设置不能小于1";
                }
                if (value > 1000) {
                    return "排序号不能大于1000";
                }
            }
        }, bigAmount: function (value) {
            if (value !== "") {
                let r = /^([1-9]\d{0,9}|0)([.]?|(\.\d{1,2})?)$/;
                if (!r.test(value)) {
                    return '格式内容不正确，请重新输入';
                }
                if (Number(value) > 100000000) {
                    return '数值不能超过100000000.00';
                }
            }
        }
    });

    zmnLayUtil.layFormVerify(form);

    upload.render({
        elem: '#scanFileUpload'
        ,url: '/common/uploadFile.action' //改成您自己的上传接口
        ,data: {folderName: 'contract'}
        ,accept: 'file' //普通文件
        ,multiple: false
        ,size:1024*25
        ,exts: 'xlsx|xls|csv|pdf|ppt|pptx|doc|docx|rar|zip|7z'
        ,done: function(res){
            var uploadFiles = document.getElementsByClassName('uploadScanFile');
            var size = uploadFiles.length;

            if (size >= 4){
                layer.alert('添加失败，附件最多不超过4个！');
                return false;
            }

            var addName = size;

            var fileSize = 0;
            fileSize = res.data.size * 1.0 / 1024;
            fileSize = fileSize.toFixed(2);
            fileSize = fileSize + 'KB';

            $("#scanFiles").append('<zmn><div class="singleFile layui-input-block">\n' +
            '                                <div class="layui-input-inline" style="width: auto">\n' +
            '                                    <a name="scanFileSrc" id="scanFileSrc'+ addName +'" href="' + res.data.src + '" class="layui-form-label uploadScanFile" style="width: auto;">' + res.data.name + '</a>\n' +
            '                                    <span name="scanFileSize" id="fileSize'+ addName +'" value="'+ res.data.size +'" class="layui-form-label" style="width: auto; color: #9F9F9F;">' + fileSize + '</span>\n' +
            '                                    <a class="layui-form-label" onclick="deleteFile(\'scanFileSrc'+ addName +'\')" style="width:auto;color: #00a0e9">\n' +
            '                                        删除\n' +
            '                                    </a>\n' +
            '                                </div>\n' +
                '                            <div class="layui-split">&nbsp;</div>\n' +
                '                        </div></zmn>');

            form.render();
            layer.msg('上传成功');
            console.log(res);
        }
    });

    upload.render({
        elem: '#sonFileUpload'
        ,url: '/common/uploadFile.action' //改成您自己的上传接口
        ,data: {folderName: 'contract'}
        ,accept: 'file' //普通文件
        ,multiple: false
        ,size:1024*25
        ,exts: 'rar|zip|7z'
        ,done: function(res){
            var uploadFiles = document.getElementsByClassName('uploadSonFile');
            var size = uploadFiles.length;

            if (size >= 4){
                layer.alert('添加失败，附件最多不超过4个！');
                return false;
            }

            var addName = size;

            var fileSize = 0;
            fileSize = res.data.size * 1.0 / 1024;
            fileSize = fileSize.toFixed(2);
            fileSize = fileSize + 'KB';

            $("#sonFiles").append('<zmn><div class="singleFile layui-input-block">\n' +
                '                                <div class="layui-input-inline" style="width: auto">\n' +
                '                                    <a name="sonFileSrc" id="sonFileSrc'+ addName +'" href="' + res.data.src + '" class="layui-form-label uploadSonFile" style="width: auto;">' + res.data.name + '</a>\n' +
                '                                    <span name="sonFileSize" id="sonFileSize'+ addName +'" value="'+ res.data.size +'" class="layui-form-label" style="width: auto; color: #9F9F9F;">' + fileSize + '</span>\n' +
                '                                    <a class="layui-form-label" onclick="deleteFile(\'sonFileSrc'+ addName +'\')" style="width:auto;color: #00a0e9">\n' +
                '                                        删除\n' +
                '                                    </a>\n' +
                '                                </div>\n' +
                '                            <div class="layui-split">&nbsp;</div>\n' +
                '                        </div></zmn>');

            form.render();
            layer.msg('上传成功');
            console.log(res);
        }
    });

    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;

        if (data.agent == null || data.agent == undefined || data.agent == '') {
            layer.msg("经办人不能为空！");
            return false;
        }

        data['agentCompanyName'] = $('#agentCompanyId option:selected').text();
        data['agentDeptOneName'] = $('#oneDeptId option:selected').text();
        data['agentDeptTwoName'] = $('#deptId option:selected').text();
        if (data.subjectAmount != null && data.subjectAmount != '' && data.subjectAmount != undefined) {
            data['subjectAmount'] = parseInt(data.subjectAmount * 100);
        } else {
            data['subjectAmount'] = 0;
        }

        let array = new Array();
        $('#scanFiles').find('.singleFile').each( function() {
            var obj = $(this);
            var contractFileRecord = new Object();
            let fileSrc = $(obj).find("a[name='scanFileSrc']").attr('href');
            let fileSize = $(obj).find("span[name='scanFileSize']").attr('value');;
            contractFileRecord['fileSrc'] = fileSrc;
            contractFileRecord['fileSize'] = fileSize;
            contractFileRecord['contractId'] = data.contractId;
            contractFileRecord['fileType'] = 2;
            array.push(contractFileRecord);
        });

        if (array.length <= 0) {
            layer.msg("合同扫描件不能为空！");
            return false;
        }

        $('#sonFiles').find('.singleFile').each( function() {
            var obj = $(this);
            var contractFileRecord = new Object();
            let fileSrc = $(obj).find("a[name='sonFileSrc']").attr('href');
            let fileSize = $(obj).find("span[name='sonFileSize']").attr('value');;
            contractFileRecord['fileSrc'] = fileSrc;
            contractFileRecord['fileSize'] = fileSize;
            contractFileRecord['contractId'] = data.contractId;
            contractFileRecord['fileType'] = 1;
            array.push(contractFileRecord);
        });

        data.contractFileRecords = array;

        let url = "/contract/record/addEdit.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                layer.close(index);
                layer.msg(json.message);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete: function () {
                layer.close(index);
            }
        })

        return false;
    });

    // 2级部门联动
    form.on('select(oneDeptId)', function (obj) {
        triggerTwoDeptOptions(obj.value);
    })

    function triggerTwoDeptOptions(value) {
        let twoDeptOptions = json.twoDepts.filter(p => p.parentId == value).map(p => {
            return p.deptId == obj.agentdeptTwoId ? '<option value="' + p.deptId + '" selected="selected">' + p.deptName + '</option>' : '<option value="' + p.deptId + '">' + p.deptName + '</option>';
        });
        twoDeptOptions.unshift('<option value=""></option>');
        $('#deptId').html(twoDeptOptions);
        form.render("select");
    }

    //点击取消
    $(document).on('click', '#cancel', function () {
        let index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
        parent.layer.close(index);
    });

    //对外暴露的接口
    exports('contract_record_detail_edit_js', {});
});

function deleteFile(element) {
    var compoent = document.getElementById(element);
    var block = compoent.parentNode.parentNode;
    var file = compoent.parentNode.parentNode.parentNode;
    var files = compoent.parentNode.parentNode.parentNode.parentNode;
    files.removeChild(file);
    form.render();
}

